#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from xml.etree.ElementTree import ElementTree


class DefineIO:

    def __init__(self, filename):
        self._filename = filename

    def read(self):
        datas = []
        tree = ElementTree(file=self._filename)
        beans = tree.getroot()
        for bean in beans:
            attr = bean.attrib
            b = Bean(attr['name'], attr['from'], attr['genxml'])
            datas.append(b)
            for v in bean:
                vattr = v.attrib
                if vattr['type'] == 'vector':
                    var = Variable(vattr['name'], vattr['fromCol'], vattr['type'], vattr['value'])
                else:
                    var = Variable(vattr['name'], vattr['fromCol'], vattr['type'])
                b.appendVariable(var)
        return datas


class Bean:

    def __init__(self, name, fromFile, genxml):
        self._name = name
        self._fromFile = fromFile
        self._genxml = genxml
        self._variables = []

    def getName(self):
        return self._name

    def getVars(self):
        return self._variables

    def getFromFile(self):
        return self._fromFile

    def appendVariable(self, variable):
        self._variables.append(variable)

    def __repr__(self):
        return '\n'.join(["""<bean name="%s" from="%s" genxml="%s" """ % (self._name, self._fromFile, self._genxml),
                          self.getVariablesStr(), '</bean>'])

    def getVariablesStr(self):
        return '\n'.join([repr(var) for var in self._variables])


class Variable:

    def __init__(self, name, fromCol, type, value=''):
        self._name = name
        self._fromCol = fromCol
        self._type = type
        self._value = value

    def getName(self):
        return self._name

    def getFromCol(self):
        return self._fromCol

    def getType(self):
        return self._type

    def getValue(self):
        return self._value

    def getExcelTag(self):
        return 'variable'

    def __repr__(self):
        if self._type == 'vector':
            return '<%s name="%s" fromCol="%s" type="%s" value="%s" />' % (self.getExcelTag(), self._name, self._fromCol, self._type, self._value)
        else:
            return '<%s name="%s" fromCol="%s" type="%s" />' % (self.getExcelTag(), self._name, self._fromCol, self._type)